﻿using IOA.MES.Client.Common;
using IOA.MES.Client.Models.Response;
using IOA.MES.Common;
using NLog;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace IOA.MES.Client.FinalInspection
{
    public delegate void SetImageDelegate(string image);
    /// <summary>
    /// WinScan.xaml 的交互逻辑
    /// </summary>
    public partial class WinScan : Window
    {
        private Logger logger = LogManager.GetCurrentClassLogger();
        private SetImageDelegate setImageDelegate;
        public InspectData InspectData { get; set; }
        private DateTime loadTime;
        private bool windowLoaded = false;
        public WinScan(SetImageDelegate del)
        {
            setImageDelegate = del;
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            txtBarCode1.Text = "";
            txtBarCode2.Text = "";
            txtBoxCode.Text = "";
            txtQCPassCode.Text = "";
            txtVerifyCode.Text = "";
            txtBarCode1.Focus();
            InspectData = new InspectData
            {
                BarCode1 = "",
                BarCode2 = "",
                BarCode3 = "",
                BoxCode = "",
                QCPassCode = "",
                VerifyCode = "",
                ComponentData = null
            };

            loadTime = DateTime.Now;
            this.Topmost = true;

            cbBarCode2.IsChecked = string.Equals(BaseEnv.GetStorage("FinalCode_BarCode2"), "1");
            cbBarCode3.IsChecked = string.Equals(BaseEnv.GetStorage("FinalCode_BarCode3"), "1");
            cbBoxCode.IsChecked = string.Equals(BaseEnv.GetStorage("FinalCode_BoxCode"), "1");
            cbQCPassCode.IsChecked = string.Equals(BaseEnv.GetStorage("FinalCode_QCPassCode"), "1");
            cbVerifyCode.IsChecked = string.Equals(BaseEnv.GetStorage("FinalCode_VerifyCode"), "1");
            windowLoaded = true;
        }

        private void cbCode_Checked(object sender, RoutedEventArgs e)
        {
            var chexkBox = sender as CheckBox;
            var senderName = chexkBox.Name.Replace("cb", "");
            var txtBox = (TextBox)FindName($"txt{senderName}");
            txtBox.IsEnabled = chexkBox.IsChecked == true;
            if (chexkBox.IsChecked != true)
            {
                txtBox.Text = "";
            }
            if (windowLoaded)
            {
                BaseEnv.SetStorage($"FinalCode_{senderName}", chexkBox.IsChecked == true ? "1" : "0");
            }
        }

        private void txtCode_KeyUp(object sender, KeyEventArgs e)
        {

            var txtBox = sender as TextBox;
            if ((DateTime.Now - loadTime).TotalMilliseconds < 200)
            {
                txtBox.Text = "";
            }
            if (e.Key != Key.Enter || string.IsNullOrWhiteSpace(txtBox.Text.Trim()))
            {
                return;
            }
            txtBox.Text = txtBox.Text.Trim().ToUpper();

            switch (txtBox.Name)
            {
                case "txtBarCode1":
                    var getFinalInspectDataResponse = BaseEnv.InvokeApi<GetFinalInspectDataResponse>("/api/NQC/GetFinalInspectData", new { BarCode = txtBarCode1.Text.ToUpper().Trim() });
                    if (getFinalInspectDataResponse.ErrCode != 200)
                    {
                        CommonMessage.Alert(this, getFinalInspectDataResponse.ErrMsg);
                        txtBarCode1.SelectAll();
                        return;
                    }
                    InspectData.ComponentData = getFinalInspectDataResponse.Data;
                    if (!string.IsNullOrWhiteSpace(InspectData.ComponentData.El2Image))
                    {
                        new TaskFactory().StartNew(new Action(() =>
                        {
                            DownloadEl2Image(InspectData.ComponentData.El2Image);
                        }));
                    }
                    break;
                case "txtBarCode2":
                    if (!string.Equals(txtBarCode1.Text.Trim(), txtBarCode2.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        InitForm(true);
                        return;
                    }
                    break;
                case "txtBarCode3":
                    if (cbBarCode2.IsChecked == true)
                    {
                        if (!string.Equals(txtBarCode2.Text.Trim(), txtBarCode3.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
                        {
                            InitForm(true);
                            return;
                        }
                    }
                    else if (!string.Equals(txtBarCode1.Text.Trim(), txtBarCode3.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
                    {
                        InitForm(true);
                        return;
                    }
                    break;
                case "txtVerifyCode":
                    if (cbVerifyCode.IsChecked == true)
                    {
                        if (string.IsNullOrEmpty(txtVerifyCode.Text.Trim()) || txtVerifyCode.Text.Trim().Length != 8)
                        {
                            InitForm2(true);
                            return;
                        }

                    }

                    break;
                default:

                    break;
            }

            if (string.IsNullOrWhiteSpace(txtBarCode1.Text))
            {
                txtBarCode1.Text = string.Empty;
                txtBarCode1.Focus();
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtBarCode2.Text) && cbBarCode2.IsChecked == true)
            {
                txtBarCode2.Text = string.Empty;
                txtBarCode2.Focus();
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtBarCode3.Text) && cbBarCode3.IsChecked == true)
            {
                txtBarCode3.Text = string.Empty;
                txtBarCode3.Focus();
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtBoxCode.Text) && cbBoxCode.IsChecked == true)
            {
                txtBoxCode.Text = string.Empty;
                txtBoxCode.Focus();
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtQCPassCode.Text) && cbQCPassCode.IsChecked == true)
            {
                txtQCPassCode.Text = string.Empty;
                txtQCPassCode.Focus();
                return;
            }
            else if (string.IsNullOrWhiteSpace(txtVerifyCode.Text) && cbVerifyCode.IsChecked == true)
            {
                txtVerifyCode.Text = string.Empty;
                txtVerifyCode.Focus();
                return;
            }
            else if ((cbBarCode2.IsChecked == true && !string.Equals(txtBarCode1.Text.Trim(), txtBarCode2.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
                || (cbBarCode3.IsChecked == true && !string.Equals(txtBarCode1.Text.Trim(), txtBarCode3.Text.Trim(), StringComparison.CurrentCultureIgnoreCase))
                || (cbVerifyCode.IsChecked == true && txtVerifyCode.Text.Trim().Length != 8))
            {
                InitForm(true);
                return;
            }

            TrySubmit();
        }

        private void InitForm(bool showError = false)
        {
            txtBarCode1.Text = string.Empty;
            txtBarCode2.Text = string.Empty;
            txtBarCode3.Text = string.Empty;
            txtBoxCode.Text = string.Empty;
            txtQCPassCode.Text = string.Empty;
            txtVerifyCode.Text = string.Empty;
            txtBarCode1.Focus();

            if (showError)
            {
                mediaMessage.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                mediaMessage.Play();
                CommonMessage.Alert(this, "条码不一致！\r\nInconsistent barcode！");
            }
        }

        private void InitForm2(bool showError = false)
        {
            txtBarCode1.Text = string.Empty;
            txtBarCode2.Text = string.Empty;
            txtBarCode3.Text = string.Empty;
            txtBoxCode.Text = string.Empty;
            txtQCPassCode.Text = string.Empty;
            txtVerifyCode.Text = string.Empty;
            txtBarCode1.Focus();

            if (showError)
            {
                mediaMessage.Source = new Uri($"{BaseEnv.LocalDirectory}\\res\\audio\\Fail.wav");
                mediaMessage.Play();
                CommonMessage.Alert(this, "请重新输入防伪码！\r\nInconsistent barcode！");
            }
        }

        private void DownloadEl2Image(string el2Image)
        {
            var folder = $"{BaseEnv.LocalDirectory}\\download\\el2Images\\{DateTime.Today:yyyyMMdd}";
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }
            var fileName = $"{folder}\\{el2Image.Substring(el2Image.LastIndexOf("/") + 1)}";
            if (File.Exists(fileName))
            {
                try
                {
                    File.Delete(fileName);
                }
                catch (Exception ex)
                {
                    fileName = $"{folder}\\{Path.GetFileNameWithoutExtension(fileName)}_{DateTime.Now.ToString("HHmmssffff")}{Path.GetExtension(fileName)}";
                }
            }
            new FtpUtils(BaseEnv.UserInfo.FtpConfig.UserName, BaseEnv.UserInfo.FtpConfig.Password).Download(el2Image, fileName);
            InspectData.ComponentData.El2Image = fileName;
            setImageDelegate(fileName);

            new TaskFactory().StartNew(() =>
            {
                var directories = Directory.GetDirectories($"{BaseEnv.LocalDirectory}\\download\\el2Images");
                foreach (var item in directories)
                {
                    try
                    {
                        if (string.Compare(item, $"{BaseEnv.LocalDirectory}\\download\\el2Images\\{DateTime.Today.AddDays(-2):yyyyMMdd}") < 0)
                        {
                            Directory.Delete(item, true);
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Fatal(ex, $"删除目录失败，目录：{item}，错误信息：{ex.Message}");
                    }
                }
            });
        }

        private void TrySubmit()
        {
            InspectData.BarCode1 = txtBarCode1.Text.Trim();
            InspectData.BarCode2 = txtBarCode2.Text.Trim();
            InspectData.BarCode3 = txtBarCode3.Text.Trim();
            InspectData.BoxCode = txtBoxCode.Text.Trim();
            InspectData.QCPassCode = txtQCPassCode.Text.Trim();
            InspectData.VerifyCode = txtVerifyCode.Text.Trim();

            this.DialogResult = true;
            this.Close();
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.DialogResult != true)
            {
                InspectData = new InspectData
                {
                    BarCode1 = "",
                    BarCode2 = "",
                    BarCode3 = "",
                    BoxCode = "",
                    QCPassCode = "",
                    VerifyCode = "",
                    ComponentData = null
                };
            }
        }
    }

    public class InspectData
    {
        public string BarCode1 { get; set; }
        public string BarCode2 { get; set; }
        public string BarCode3 { get; set; }
        public string BoxCode { get; set; }
        public string QCPassCode { get; set; }
        public string VerifyCode { get; set; }
        public GetFinalInspectDataResponse ComponentData { get; set; }
    }
}
